<?php
class CPageLayout
{
	public $layout = false;
	static $layout_tags = array(
		'REGION' => '\[\[\|(\w+)\|\]\]'
	);
	function __construct($layout)
	{
		$this->layout = $layout;
	}
	function build($blocks, $parent_id = 0)
	{
		require_once 'lib/utils/CTranslation.php';
		require_once 'lib/utils/CToken.php';
		$tokens = CTranslation($this->layout, CPageLayout::$layout_tags)->tokenize();
		$code = '';
		$component_groups = CList(CList($blocks)->filter(array('parent_id'=>$parent_id)))->group('region');
		foreach($tokens as $token)
		{
			$token = CToken($token);
			switch($token->type)
			{
			case 'TEXT':
				$code .= $token->param;
				break;
			case 'REGION':
				$code .= $this->build_region($token->param, isset($component_groups[$token->param])?$component_groups[$token->param]:array());
				break;
			}
		}
		return $code;
	}
	function build_region($region, $blocks)
	{
		if($blocks)
		{
			$code = '<?php ';
			foreach($blocks as $index=>$block)
			{
				$code .= 'CPage::$current->all_blocks['.$index.']->draw();';
			}
			$code .= ' ?>';
		}
		else
		{
			$code = '';
		}
		return $code;
	}
}
function CPageLayout($layout)
{
	return new CPageLayout($layout);
}
?>